package com.hh.demo.controller;

import com.hh.demo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
    /**
     * 登录操作
     */
    @GetMapping(value = {"/","/login"})
    public String login(){
        return "login";
    }
    @PostMapping("/login1")
    public String main(User user, HttpSession session, Model model) {
        if (StringUtils.hasLength(user.getUsername()) && "123456".equals(user.getPassword())) {
            //把登录成功的用户保存起来
            session.setAttribute("loginUser", user);
            //登陆成功：重定向到index 页面
            return "redirect:/index.html";
        } else if (!(StringUtils.hasLength(user.getUsername()))&& "".equals(user.getPassword())) {
            model.addAttribute("msg", "账号/密码不能为空");
            return "login";
        } else{
            model.addAttribute("msg", "账号/密码错误");
            //回到登录页面
            return "login";
        }
    }
    @GetMapping("/index.html")
    public String index(HttpSession session,Model model) {
        //判断是否登录(来个简单的判断，这部分内容应该交给拦截器来写)
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser!=null){
            return "index";
        }else{
            //回到登陆页面
            model.addAttribute("msg","请重新登录");
            return "login";
        }
    }
}
